package com.writing.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.writing.common.Result;
import com.writing.entity.Novel;
import com.writing.service.NovelService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;

/**
 * 小说控制器
 */
@RestController
@RequestMapping("/novels")
@RequiredArgsConstructor
public class NovelController {
    
    private final NovelService novelService;
    
    /**
     * 分页获取用户小说列表
     */
    @GetMapping
    public Result<IPage<Novel>> getNovels(
            @RequestAttribute("userId") Long userId,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        
        IPage<Novel> novels = novelService.getUserNovels(userId, current, size);
        return Result.success(novels);
    }
    
    /**
     * 获取用户所有小说列表
     */
    @GetMapping("/list")
    public Result<List<Novel>> getNovelList(@RequestAttribute("userId") Long userId) {
        List<Novel> novels = novelService.getUserNovelList(userId);
        return Result.success(novels);
    }
    
    /**
     * 获取小说详情
     */
    @GetMapping("/{id}")
    public Result<Novel> getNovel(
            @RequestAttribute("userId") Long userId,
            @PathVariable Long id) {
        
        Novel novel = novelService.getNovelDetail(userId, id);
        if (novel == null) {
            return Result.error("小说不存在");
        }
        return Result.success(novel);
    }
    
    /**
     * 创建小说
     */
    @PostMapping
    public Result<Novel> createNovel(
            @RequestAttribute("userId") Long userId,
            @RequestBody @Valid Novel novel) {
        
        try {
            Novel createdNovel = novelService.createNovel(userId, novel);
            return Result.success("创建成功", createdNovel);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新小说
     */
    @PutMapping("/{id}")
    public Result<Novel> updateNovel(
            @RequestAttribute("userId") Long userId,
            @PathVariable Long id,
            @RequestBody @Valid Novel novel) {
        
        try {
            novel.setId(id);
            Novel updatedNovel = novelService.updateNovel(userId, novel);
            return Result.success("更新成功", updatedNovel);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除小说
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteNovel(
            @RequestAttribute("userId") Long userId,
            @PathVariable Long id) {

        try {
            boolean deleted = novelService.deleteNovel(userId, id);
            if (deleted) {
                return Result.success();
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 上传小说文件
     */
    @PostMapping("/upload")
    public Result<Novel> uploadNovel(
            @RequestAttribute("userId") Long userId,
            @RequestParam("file") MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("genre") String genre,
            @RequestParam("encoding") String encoding,
            @RequestParam(value = "autoSplit", defaultValue = "true") Boolean autoSplit,
            @RequestParam(value = "description", required = false) String description) {

        try {
            Novel novel = novelService.uploadNovel(userId, file, title, genre, encoding, autoSplit, description);
            return Result.success("上传成功", novel);
        } catch (Exception e) {
            return Result.error("上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新小说字数统计
     */
    @PostMapping("/{id}/update-word-count")
    public Result<Void> updateWordCount(@PathVariable Long id) {
        try {
            novelService.updateWordCount(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
